package com.test.platform.module.system.service;

import com.test.common.component.RedisComponent;
import com.test.common.entity.perf.PerfTaskEntity;
import com.test.common.entity.system.PermissionImpl;
import com.test.common.entity.system.User;
import com.test.common.enums.system.PermissionLevelEnum;
import com.test.common.repository.system.PermissionRepository;
import com.test.common.repository.system.UserRepository;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.transaction.Transactional;

@Service
public class PermissionService {

    @Resource
    private PermissionRepository permissionRepository;

    @Resource
    private UserRepository userRepository;

    @Resource
    private RedisComponent redisCommonUtil;

    // 给用户添加性能任务权限
    @Transactional(rollbackOn = Exception.class)
    public User initPerfTaskPermission(PerfTaskEntity perfTaskEntity) {

        User user = (User) SecurityUtils.getSubject().getPrincipal();
        user = userRepository.findByName(user.getName());

        // 创建权限，当前用户直接添加管理员权限
        permissionRepository.save(new PermissionImpl(PermissionLevelEnum.READ, perfTaskEntity));
        permissionRepository.save(new PermissionImpl(PermissionLevelEnum.READ_WRITE, perfTaskEntity));
        user.getPermissions().add(permissionRepository.save(new PermissionImpl(PermissionLevelEnum.ADMIN, perfTaskEntity)));

        return userRepository.save(user);
    }
}
